<?php

namespace app\shop\controller\product;

use app\shop\controller\Controller;
use app\shop\model\product\Category as CategoryModel;

/**
 * 商品分类
 */
class Category extends Controller
{
    /**
     * 商品分类列表
     */
    public function index()
    {
        $model = new CategoryModel;
        $param = $this->postData();
        $list  = $model->getCacheTree(2, $param);
        // 数量
        $proxyCate = new \app\proxy\model\product\ProxyCategory();
        $category_count = [
            'using'   => $proxyCate->getTotalByWhere(['audit_status' => 1]),
            'audit'   => $proxyCate->getTotalByWhere(['audit_status' => 0]),
            'no_pass' => $proxyCate->getTotalByWhere(['audit_status' => 2]),
        ];
        return $this->renderSuccess('', compact('list', 'category_count'));
    }

    /**
     * 删除商品分类
     */
    public function delete($category_id)
    {
        $model = (new CategoryModel())->find($category_id);
        if ($model->remove($category_id)) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * 添加商品分类
     */
    public function add()
    {
        $model = new CategoryModel;
        // 新增记录
        if ($model->add($this->request->post())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑商品分类
     */
    public function edit($category_id)
    {
        // 模板详情
        $model = CategoryModel::detail($category_id);
        // 更新记录
        if ($model->edit($this->request->post())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 权限状态
     */
    public function status($category_id, $status)
    {
        $model = CategoryModel::detail($category_id);
        if ($model->status($status)) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($model->getError() ?:'修改失败');
    }

    /**
     * 得到修改图片
     * @return array
     */
    public function image($category_id)
    {
        $model  = new CategoryModel;
        $detail = $model->detailWithImage(['category_id' => $category_id]);
        return $this->renderSuccess('', compact('detail'));
    }

    /**
     * 审核商品分类
     * @return \think\response\Json
     * @Author joey
     * @date 2024/3/27 10:55
     */
    public function audit()
    {
        $param  = $this->postData();
        $model  = new CategoryModel;
        $detail = $model->find($param['category_id']);
        if ($detail->isEmpty()) {
            return $this->renderError('分类不存在');
        }
        $res = $detail->allowField(['audit_status', 'remark'])->save($param);
        return $this->renderSuccess($res ? '审核成功' : '审核失败');
    }


}
